package com.wz.leetcode.backtrack;

import java.util.*;


public class CombinationSum_39 {
    public static List<List<Integer>> combinationSum(int[] candidates, int target) {
        int len = candidates.length;
        List<List<Integer>> result = new ArrayList<>();
        if (len == 0) {
            return result;
        }
        // 排序，剪枝
        Arrays.sort(candidates);
        Deque<Integer> path = new ArrayDeque<>();
        dfs(candidates, 0, len, target, path, result);
        return result;
    }

    private static void dfs(int[] candidates,
                     int begin,
                     int len,
                     int target,
                     Deque<Integer> path,
                     List<List<Integer>> result) {
        if (target == 0) {
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = begin; i < len; i++) {
            // candidates升序排列，后面更大
            if (target - candidates[i] < 0) {
                break;
            }
            path.addLast(candidates[i]);
            // 可重复取i，因此这里第一个index还是取i
            dfs(candidates, i, len, target - candidates[i], path, result);
            path.removeLast();
        }
    }

    public static void main(String[] args) {
        System.out.println(combinationSum(new int[]{2, 3, 6, 7}, 7));
        System.out.println(combinationSum(new int[]{2, 3, 5}, 8));
        System.out.println(combinationSum(new int[]{2}, 1));
    }
}
